package view {
	import flash.display.Sprite;
	import flash.filters.GlowFilter;
	import flash.geom.Rectangle;
	import model.PiecesDefination;
	
	/**
	 * ...
	 * @author flyingSnow
	 */
	public final class Piece extends Sprite {
		private var _layer:Sprite;
		private var _squarePool:Array;
		private var _piece:int;
		private var _direction:int;
		private var _crntColorIndex:int;
		
		public function Piece() {
			super();
			addSquares();
		}
		
		private function addFilter():void {
			this.filters = [new GlowFilter(0,1,4,4,2)];
		}
		private function removeFilter():void {
			this.filters = [new GlowFilter(0,0.5,4,4,1)];
		}
		
		private function addSquares():void {
			_layer = new Sprite();
			addChild(_layer);
			
			_squarePool = [];
			
			for (var i:int = 0; i < 5; i++ ) {
				for (var j:int = 0; j < 5; j++ ) {
					var newSqu:Square = new Square();
					_layer.addChild(newSqu);
					newSqu.state = 0;
					newSqu.colorIndex = 4;
					newSqu.x = Square.STANDARD_SIZE * (4-j);
					newSqu.y = Square.STANDARD_SIZE * i;
					_squarePool.push(newSqu);
				}
			}
		}
		public function shapeArray(piece:int, direction:int):void {
			this._direction = direction;
			this._piece = piece;
			
			var value:Array = PiecesDefination.PIECES_DEF[piece][direction];
			for (var i:int = 0; i < 5; i++ ) {
				for (var j:int = 0; j < 5; j++ ) {
					var square:Square = (_squarePool[i * 5 + j] as Square);
					var state:uint=((value[i] as uint) >> (4-j)) & 1;
				
					square.state = state;
					//square.visible = Boolean(state);
					if (state) {
						_layer.addChild(square);
					}else if(square.parent){
						square.parent.removeChild(square);
					}
				}
			}
			
			//_layer.x =	-Square.STANDARD_SIZE*5+_layer.width/2;
			//_layer.y =	-_layer.height/2;
			
		}
		

		
		public function get pieceIndex():int {
			return _piece;
		}
		
		public function get direction():int {
			return _direction;
		}
		
		public function get crntColorIndex():int {
			return _crntColorIndex;
		}
		public function set crntColorIndex(colorIndex:int):void {
			_crntColorIndex = colorIndex;
			for each(var squ:Square in _squarePool) {
				squ.colorIndex = colorIndex;
			}
			
			if (colorIndex == Square.UNABLED_INDEX) {
				removeFilter();
			}else {
				addFilter();
			}
		}		
		//public function set crntColorIndex(value:int):void {
			//_crntColorIndex = value;
		//}
	}

}